<?php
  /**
   * @author EVANDRO DE OLIVEIRA.
   * @category CONTROLLER
   * @package CONTROLLERS.
   * @since 17/03/2012.
   * @last_update 24/03/2012.
   * @copyright 2012.
   * @version 1.0.
   *
   */
  class AccountController extends Zend_Controller_Action{
    public function init(){}
    
    public function indexAction(){
    	$this->_forward('login');  
    }
    
    public function loginAction(){                	
    	$strDate = new Zend_Date();
                
      $this->_helper->layout->disableLayout();
      
      $objAuthNamespace = new Zend_Session_Namespace('Zend_Auth');

      /* Carregando a library captcha*/
      $this->db = new Core_Auth_Captcha();
      
      /* Enviando o captcha para a tela.*/
      $this->view->captcha = $this->db->generateCaptcha();

      // Testa se houve POST.
      if($this->_request->isPost()){
        //Instancia a classe Zend_Filter_StripTags.
        $objFilter = new Zend_Filter_StripTags();
        
        // Armazena o e-mail e senha do usuario.
        $strDsLogin     = $objFilter->filter($this->_request->getPost('ds_login'));
        $strDsPassword  = $objFilter->filter($this->_request->getPost('ds_password'));
        $strDscaptcha   = $objFilter->filter($this->_request->getPost('ds_captcha'));
        $intIdCaptcha   = $objFilter->filter($this->_request->getPost('idCaptcha'));
      
        if(isset($strDsLogin) && empty($strDsLogin) || isset($strDsPassword) && empty($strDsPassword)){
        	$objAuthNamespace->tentativa++;
          Core_FlashMessage::addMessage('Por favor, forneça o e-mail e senha.', '3');          
          //new Core_ZendLog('E-MAIL OU SENHA NAO FORNECIDO', 'LOG', 'WARN');
        }
        else{
        	// Conectando a base de dados.
        	$objDbAdapter = Zend_Registry::get('adapter');
        	
        	$objAuthAdapter = new Zend_Auth_Adapter_DbTable($objDbAdapter);
          
          $objAuthAdapter->setTableName('funcionarios');
          $objAuthAdapter->setIdentityColumn('ds_login');
          $objAuthAdapter->setCredentialColumn('ds_senha');
          $objAuthAdapter->setCredentialTreatment('MD5(?)');
          
          $objAuthAdapter->setIdentity($strDsLogin);
          $objAuthAdapter->setCredential($strDsPassword);
          
          $objAuth = Zend_Auth::getInstance();
          
          $objResult = $objAuth->authenticate($objAuthAdapter);
          
          if($objResult->isValid()){          	
          	if($objAuthNamespace->tentativa >= 3){
              $objAuthNamespace->tentativa++;
                
              // Carregando a validação do captcha.
              $objValidate = $this->db->validateCaptcha($strDscaptcha, $intIdCaptcha);
              if(!$objValidate)
                Core_FlashMessage::addMessage('Dado digitado não confere com a imagem do captcha.', '4');
              else
                $this->autentica($strDsLogin, $objAuthAdapter, $objAuth);
            }
            else
              $this->autentica($strDsLogin, $objAuthAdapter, $objAuth);  
          }
          else{
          	$objAuthNamespace->tentativa++;
          	Core_FlashMessage::addMessage('Login ou senha inválidos.', '4');
            //new Core_ZendLog('LOGIN OU SENHA INVÁLIDOS', 'LOG', 'WARN');
          }
        } 
      }
      else
        //$log = new Core_ZendLog('USUÁRIO NÃO LOGADO', 'LOG', 'INFO');
        $log = '';
    }
    
    public function autentica($strDsLogin, $objAuthAdapter, $objAuth){
    	// Ativar o uso de sessão.
      $objAuthNamespace = new Zend_Session_Namespace('Zend_Auth');
      
      $arrReturnColluns = array(
        'idFuncionario',
        'idCidade',
        'idPerfil',  
        'idUnidade',  
        'ds_matricula',  
        'ds_nome', 
        'ds_cpf',  
        'ds_rg',   
        'ds_sexo',  
        'dt_nascimento',    
        'ds_endereco',  
        'nr_residencia',
        'ds_complemento',  
        'ds_cep',  
        'ds_bairro',
        'ds_email', 
        'ds_fone',  
        'ds_cel',  
        'ds_mae',  
        'ds_pai',  
        'dt_admissao',  
        'hr_inicio',
        'hr_final',
        'ds_foto',  
        'ds_login',  
        'dt_insercao',           
        'dt_atualizacao',  
        'st_funcionario'
      );
      
      $objData = $objAuthAdapter->getResultRowObject($arrReturnColluns);
      $strPass = Zend_Registry::getInstance()->config->default->pass;
      
      if($objData->ds_password == md5($strPass)){
      	$objAuthNamespace->ds_login = $strDsLogin;
      	$objAuth->getStorage()->write($objAuthNamespace);
      	$this->_redirect('account/altera-senha'); 
      }
      
      if($objAuthNamespace == ''){
      	$objAuthNamespace->tentativa++;
      	Core_FlashMessage::addMessage('O login "' . $strDsLogin . '" não possui permissão de acesso. Contate o administrador do sistema.', '4');          
      	//new Core_ZendLog('USUÁRIO ' . $strDsLogin . ' NÃO POSSUI PERMISSÃO DE ACESSO', 'LOG', 'ERR');
      }
      else{
      	$objAuthNamespace->idFuncionario   = $objData->idFuncionario;
        $objAuthNamespace->idCidade        = $objData->idCidade;
        $objAuthNamespace->idPerfil        = $objData->idPerfil;  
        $objAuthNamespace->idUnidade       = $objData->idUnidade;  
        $objAuthNamespace->ds_matricula    = $objData->ds_matricula;  
        $objAuthNamespace->ds_nome         = $objData->ds_nome; 
        $objAuthNamespace->ds_cpf          = $objData->ds_cpf;  
        $objAuthNamespace->ds_rg           = $objData->ds_rg;   
        $objAuthNamespace->ds_sexo         = $objData->ds_sexo;   
        $objAuthNamespace->dt_nascimento   = $objData->dt_nascimento;    
        $objAuthNamespace->ds_endereco     = $objData->ds_endereco;  
        $objAuthNamespace->nr_residencia   = $objData->nr_residencia;
        $objAuthNamespace->ds_complemento  = $objData->ds_complemento;  
        $objAuthNamespace->ds_cep          = $objData->ds_cep;  
        $objAuthNamespace->ds_bairro       = $objData->ds_bairro;
        $objAuthNamespace->ds_email        = $objData->ds_email; 
        $objAuthNamespace->ds_fone         = $objData->ds_fone;  
        $objAuthNamespace->ds_cel          = $objData->ds_cel;  
        $objAuthNamespace->ds_mae          = $objData->ds_mae;  
        $objAuthNamespace->ds_pai          = $objData->ds_pai;  
        $objAuthNamespace->dt_admissao     = $objData->dt_admissao;  
        $objAuthNamespace->hr_inicio       = $objData->hr_inicio;
        $objAuthNamespace->hr_final        = $objData->hr_final;
        $objAuthNamespace->ds_foto         = $objData->ds_foto;  
        $objAuthNamespace->ds_login        = $objData->ds_login;  
        $objAuthNamespace->dt_insercao     = $objData->dt_insercao;           
        $objAuthNamespace->dt_atualizacao  = $objData->dt_atualizacao;  
        $objAuthNamespace->st_funcionario  = $objData->st_funcionario;
        
        $objAuth->getStorage()->write($objAuthNamespace);
        if($objAuthNamespace->idPerfil == 1 || $objAuthNamespace->idPerfil == 2 || $objAuthNamespace->idPerfil == 4 || $objAuthNamespace->idPerfil == 5){
          $strDsIp = $this->getIp();
          $objDaoControlAccess = new Application_Model_ControlAccess();
          $objStart = $objDaoControlAccess->startingWork($objAuthNamespace->idFuncionario, $strDsIp);
          if($objStart){
            //new Core_ZendLog('USUÁRIO LOGADO EM ' . $strDate, 'LOG', 'INFO');
            $this->_redirect('index/start'); 
          }
          else{
          	$objAuthNamespace->tentativa++;
          	Core_FlashMessage::addMessage('Ocorreu algum problema na autenticação. Tente novamente!', '4');          
          	//new Core_ZendLog('ERRO NA AUTENTICAÇÃO', 'LOG', 'ERR');
          }
        }
        else{
        	$objAuthNamespace->tentativa++;
        	Core_FlashMessage::addMessage('Autenticação inválida! Tente Novamente!', '4');   
        	//new Core_ZendLog('AUTENTICAÇÃO INVÁLIDA!', 'LOG', 'WARN');
        }
      }
    }
    
    public function alteraSenhaAction(){
    	$this->_helper->layout->disableLayout();
      
    	$authNamespace = new Zend_Session_Namespace('Zend_Auth');
    	
    	$this->view->login = $authNamespace->login;
    	
    	if($this->_request->isPost()){
    		$adapter             = Zend_Registry::getInstance()->config->mis->adapter; 
        $params['host']      = Zend_Registry::getInstance()->config->mis->host;
        $params['username']  = Zend_Registry::getInstance()->config->mis->username;
        $params['password']  = Zend_Registry::getInstance()->config->mis->password;
        $params['dbname']    = Zend_Registry::getInstance()->config->mis->dbname;
        
        $dbAdapter = Zend_Db::factory($adapter, $params);
        
    		$filter = new Zend_Filter_StripTags();
    		
    		$ds_login = $filter->filter($this->_request->getPost('login'));
    		
    		$current_pass = $filter->filter($this->_request->getPost('current_password'));
    		
    		$new_pass = $filter->filter($this->_request->getPost('new_password'));
    		
    		$data['password'] = md5($new_pass);
    		
    		$where = "login = '" . $ds_login . "' AND password = '" . md5($current_pass) . "'";
    		
    		$update = $dbAdapter->update('MASTER_USER', $data, $where);
    		//$update = true;
    		
    		if($update){
    			$returnColluns = array('nivel_acesso', 'formulario', 'login', 'EPS', 'site', 'grupo', 'operacao');
    			
    			$table = array('mu' => 'MASTER_USER');
    			
    			$select = $dbAdapter->select()->from($table, $returnColluns)->where('login = ?', $ds_login)->where('password = ?', md5($new_pass));
    			
    			$array_data = $dbAdapter->fetchRow($select);
    			
    			$result = (object)$array_data;
    			
    			if($result){
    				$this->sendSession($authNamespace, $result);
    			}
    			else{
    				$this->view->box(
              array(
                'message' => 'Logins ou senha inválidos.',
                'icon'    => 'error',
                'link'    => 'login'
              )
            );
    			}
    		}
    		else{
    			$this->view->box(
            array(
              'message' => 'Ocorreu algum problema para alterar sua senha. Contate o administrador do sistema.',
              'icon'    => 'error',
              'link'    => 'login'
            )
          );
    		}
    	}
    }
    
    /**
     * Salva as configurações de acesso na sessão.
     * 
     * @param object $objAuthNamespace - Namespace da sessão
     * @param object $objData - Dados do usuário.
     * 
     */
    private function saveSession($objAuthNamespace, $objData){
    	if($objAuthNamespace && $objData){
    		$objAuthNamespace->ds_member          = $objData->ds_member;
    		$objAuthNamespace->ds_email_staff     = $objData->ds_email_staff;
    		$objAuthNamespace->ds_phone_home      = $objData->ds_phone_home;
    		$objAuthNamespace->ds_phone_mobile    = $objData->ds_phone_mobile;
    		$objAuthNamespace->ds_address         = $objData->ds_address;
    		$objAuthNamespace->ds_zipcode         = $objData->ds_zipcode;
    		$objAuthNamespace->idCity             = $objData->idCity;
    		$objAuthNamespace->ds_rg              = $objData->ds_rg;
    		$objAuthNamespace->ds_cpf             = $objData->ds_cpf;
    		$objAuthNamespace->dt_birth           = $objData->dt_birth;
    		$objAuthNamespace->ds_sex             = $objData->ds_sex;
    		$objAuthNamespace->hr_init_work       = $objData->hr_init_work;
    		$objAuthNamespace->hr_final_work      = $objData->hr_final_work;
    		$objAuthNamespace->dt_admission       = $objData->dt_admission;
    		$objAuthNamespace->ds_email_work      = $objData->ds_email_work;
    		$objAuthNamespace->ds_phone_work      = $objData->ds_phone_work;
    		$objAuthNamespace->nr_cost_value      = $objData->nr_cost_value;
    		$objAuthNamespace->idCostCenter       = $objData->idCostCenter;
    		$objAuthNamespace->ds_photo           = $objData->ds_photo;
    		$objAuthNamespace->ds_login           = $objData->ds_login;
    		$objAuthNamespace->idProfile          = $objData->idProfile;
    		$objAuthNamespace->dt_created         = $objData->dt_created;  
    		$objAuthNamespace->dt_updated         = $objData->dt_updated;
    		$objAuthNamespace->dt_first_login     = $objData->dt_first_login; 
    		$objAuthNamespace->dt_current_login   = $objData->dt_current_login; 
    		$objAuthNamespace->dt_last_login      = $objData->dt_last_login; 
    		$objAuthNamespace->dt_last_logout     = $objData->dt_last_logout;
    		$objAuthNamespace->st_member          = $objData->st_member;
    		$objAuthNamespace->ds_lastip          = $objData->ds_lastip;
    		$objAuthNamespace->ds_comments        = $objData->ds_comments;
    		
    		$objAuth = Zend_Auth::getInstance();
    		
    		$objAuth->getStorage()->write($objAuthNamespace);
    		
    		$boolVerifySession = $this->verifyPermission($objAuthNamespace->idProfile);
    		
    	  if($boolVerifySession == true){
    	  	$this->saveControlLogin($authNamespace->login);
    	  }
    	  else{
    	  	$this->view->box(
    	  	  array(
    	  	    'message' => 'Você não tem permissão para acessar o sistema. Contate o Administrador do sistema.',
    	  	    'icon'    => 'error',
    	  	    'link'    => 'login'
    	  	  )
    	  	);
    	  }
    	}
    }
    
    /**
     * Verifica as permissões de acesso de cada usuário.
     * 
     * @param integer $intIdProfile - Id do perfil do usuário.
     * 
     * @return boolean $bollReturn - True em caso de sucesso, false em caso de falha.
     */
    private function verifyPermission($intIdProfile){
    	if($intIdPerfil){
    		if($intIdProfile == 1 || $intIdProfile == 2 || $intIdProfile == 3 || $intIdProfile == 4){
    			$bollReturn = true;
    		}
    		else{
    			$bollReturn = false;
    		}    
    	}
    	else{
    		$bollReturn = false;
    	}
    	
    	return $bollReturn;
    }
    
    /**
     * Salva as informações do usuário em caso de sucesso.
     * 
     * @param String $strDsLogin - Login do Usuário
     */
    private function saveControlAccess($strDsLogin){
      $objDaoControlAccess = new Application_Model_ControlAccess();
      
      $strIp = $this->getIp();
      
      $objAccess = $objDaoControlAccess->startingWork($strDsLogin, $strIp);
      
      if($objAccess){
      	$this->_redirect('index/start');  
      }
      else{
      	$this->view->box(
      	  array(
      	    'message' => 'Ocorreu algum problema na autenticação. Tente novamente!',
      	    'icon'    => 'error',
      	    'link'    => 'login'
      	  )
      	);
      }
    }
    
    /**
     * Retorna o IP Atual.
     * 
     * @return String $strReturn - IP ATUAL.
     */
    private function getIp(){
      $arrVariables = array('REMOTE_ADDR');
      
      $strReturn = 'Unknown';
      
      foreach($arrVariables as $strVariable){
        if(isset($_SERVER[$strVariable])){
          $strReturn = $_SERVER[$strVariable];
          
          break;
        }
      }
      
      return $strReturn;
    }
    
    
    /**
     * Finaliza e redireciona para a tela de login.
     */
    public function logoutAction(){
    	$strDate = new Zend_Date();
    	
    	/* Carregando a library captcha*/
      $this->db = new Core_Auth_Captcha();
      
      /* Enviando o captcha para a tela.*/
      $this->view->captcha = $this->db->generateCaptcha();
      
      $objDaoControlAccess = new Application_Model_ControlAccess();
                
      $strIp = $this->getIp();
      
      $intFuncionario = Zend_Auth::getInstance()->getIdentity()->idFuncionario;
      $objExit = $objDaoControlAccess->finishingWork($intFuncionario, $strIp);
      
      if($objExit){
      	//new Core_ZendLog('USUÁRIO ' . $strDsLogin . ' SAIU DO SISTEMA EM ' . $strDate, 'LOG', 'WARN');
        
        Zend_Auth::getInstance()->clearIdentity();
      
        session_destroy();
      
        $this->_redirect($this->view->controllerName . '/login');   
      }
      else{
        $this->_redirect('index/start');
      }
    }
  }